<template>
  <div>
    <mt-header title="登录" style="background-color:#f0acac;">
      <mt-button icon="back" slot="left"></mt-button>
      <router-link to="/register" slot="right">注册</router-link>
    </mt-header>
    <mt-field type="text" placeholder="请输入用户名" label="用户名" v-model="name" :state='nameState' @blur.native.capture="checkName"></mt-field>
    <mt-field type="password" placeholder="请输入密码" label="密码" v-model="pwd" :state='pwdState' @blur.native.capture="checkPwd"></mt-field>
   <br><br>
    <mt-button  type="primary" size="large" @click="checkForm" style="background-color:#f0acac;">立即登录</mt-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name:'',
      nameState:"",
      pwd:'',
      pwdState:'',
    }
  },
  methods: {
    checkForm() {
     this.checkName();//调用验证用户名的验证函数
     this.checkPwd();
    
     if(this.nameState == 'success' && this.pwdState == 'success'){
      console.log("开始登录");
       // 发送axios请求 ,执行注册业务 post请求
      let uname = this.name
      let upwd =this.pwd
      this.axios.post('/login',`username=${uname}&password=${upwd}`).then(res=>{
        console.log(res);
        // 对响应结果进行判断
        if(res.data.code == 200){
          this.$toast({
            message:'登录成功',
            duration:3000,
            position:'buttom'
          })
          // 调用vuex的mutations 修改登录状态
          this.$store.commit('loginOK',this.name)
          //将ilogin与name存入sessionStorage
          window.sessionStorage.setItem('islogin',true)
          sessionStorage.setItem('name',this.name)//window.可以省略

          this.$router.push('/')
        }else{
          this.$messagebox('提示','密码错误')
        }
      })
     }
     
    },
  
  checkName(){
     // 验证表单
     let reg = /^\w{6,15}$/;
     if(reg.test(this.name)){
       this.nameState = 'success'
     }else{
       this.nameState = 'error'
     }
  },
  checkPwd(){
    let reg = /^\d{6}$/;
     if(reg.test(this.pwd)){
       this.pwdState = 'success'
     }else{
       this.pwdState = 'error'
     }
   },
   
  },
};
</script>

<style scoped></style>
